package com.qf.service.impl;

import com.qf.cache.DefaultRoleCache;
import com.qf.cache.RoleCache;
import com.qf.entity.SysDefaultRole;
import com.qf.entity.SysRole;
import com.qf.entity.SysUserInfo;
import com.qf.entity.SysUserInfoExample;
import com.qf.exceptions.AddDataException;
import com.qf.exceptions.MyBaseException;
import com.qf.exceptions.QueryDataException;
import com.qf.exceptions.ResultCode;
import com.qf.mapper.SysUserInfoDao;
import com.qf.mapper.SysUserInfoMapper;
import com.qf.pojo.CheckType;
import com.qf.service.UserService;
import com.qf.utils.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @Author ztf
 * @Date 19:35 2021/12/27
 * UserService实现类
 **/
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class UserServiceImpl implements UserService {
    private SysUserInfoDao sysUserInfoDao;
    private SysUserInfoMapper sysUserInfoMapper;

    private DefaultRoleCache defaultRoleCache;
    private RoleCache roleCache;

    @Autowired
    public void setSysUserInfoDao(SysUserInfoDao sysUserInfoDao) {
        this.sysUserInfoDao = sysUserInfoDao;
    }

    @Autowired
    public void setSysUserInfoMapper(SysUserInfoMapper sysUserInfoMapper) {
        this.sysUserInfoMapper = sysUserInfoMapper;
    }

    @Autowired
    public void setDefaultRoleCache(DefaultRoleCache defaultRoleCache) {
        this.defaultRoleCache = defaultRoleCache;
    }

    @Autowired
    public void setRoleCache(RoleCache roleCache) {
        this.roleCache = roleCache;
    }

    @Override
    public void addUser(SysUserInfo sysUserInfo) {
        //设置断言校验参数是否为空，为空则抛出异常
        Assert.isTrue(!sysUserInfo.isEmpty(CheckType.ADD), () -> {
            throw new MyBaseException("addUser有必要参数为空", ResultCode.USERNAME_NULL);
        });

        //根据用户名或者手机号或者邮箱查询用户
        List<SysUserInfo> currentUser = sysUserInfoMapper.selectByUserNameOrPhoneOrEmail(sysUserInfo.getUsername(), sysUserInfo.getPhone(), sysUserInfo.getEmail());


        //如果currentUser不为空则抛出异常
        Assert.isTrue(currentUser.size() == 0, () -> {
            throw new AddDataException("UserServiceImpl:addUser账号已存在", ResultCode.DATA_ALREADY_EXIST);
        });

        //获取密码并以MD加盐
        String password = sysUserInfo.getPassword();
        //生成盐
        String salt = Md5Utils.getRandomString(15);

        //将盐与密码拼接
        String passwordMd5 = Md5Utils.getMd5(password, salt, 15);
        sysUserInfo.setPassword(passwordMd5);
        sysUserInfo.setPwdSalt(salt);
        //获取用户的默认角色
        SysDefaultRole defaultRole = defaultRoleCache.getValue("user");
        SysRole roleCacheValue = roleCache.getValue(defaultRole.getRoleId());
        sysUserInfo.setCreateBy(sysUserInfo.getUsername());
        sysUserInfo.setCreateTime(new Date());

        //设置用户标识
        sysUserInfo.setRemark(roleCacheValue.getRemark());
        //调sysUserInfoDao
        sysUserInfoDao.insertSelective(sysUserInfo);
    }


    @Override
    public SysUserInfo login(String username, String password) {
        //判断参数是否为空
        Assert.isTrue(StringUtils.hasText(username) && StringUtils.hasText(password), () -> {
            throw new QueryDataException("账号或者密码错误UserServiceImpl:login", ResultCode.USERNAME_PASSWORD_ERROR);
        });
        //如果参数不为空，则用username查询，如果查询结果为空则账号错误
        SysUserInfo userInfo = sysUserInfoMapper.selectByUserName(username);
        Assert.notNull(userInfo, () -> {
            throw new QueryDataException("账号或者密码错误UserServiceImpl:login", ResultCode.USERNAME_PASSWORD_ERROR);
        });

        //如果查询结果不为空则比对密码，
        //先将用户输入的密码进行加盐处理
        String passwordMd5 = Md5Utils.getMd5(password, userInfo.getPwdSalt(), 15);
        //将用户输入密码处理后与数据库储存密码对比，如果一致则登陆成功，不一致则抛出异常
        Assert.isTrue(passwordMd5.equalsIgnoreCase(userInfo.getPassword()), () -> {
            throw new QueryDataException("账号或者密码错误UserServiceImpl:login", ResultCode.USERNAME_PASSWORD_ERROR);
        });

        //将密码与盐清空，保证安全性
        userInfo.setPassword(null);
        userInfo.setPwdSalt(null);

        //返回用户信息
        return userInfo;
    }

    @Override
    public int updateUserLogin(SysUserInfo userInfo) {
        sysUserInfoMapper.updateUserLogin(userInfo);
        return 0;
    }

    @Override
    public SysUserInfo findUserByUserName(String username) {
        SysUserInfoExample sysUserInfoExample = new SysUserInfoExample();
        SysUserInfoExample.Criteria sysUserInfoExampleCriteria = sysUserInfoExample.createCriteria();
        sysUserInfoExampleCriteria.andUsernameEqualTo(username);

        List<SysUserInfo> sysUserInfoList = sysUserInfoDao.selectByExample(sysUserInfoExample);
        Assert.isTrue(!sysUserInfoList.isEmpty(), () -> {
            return null;
        });
        return sysUserInfoList.get(0);
    }
}
